<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px;"
          suffix-icon="Search"
          :suffix-icon-style="{ color: '#909399' }"
          :placeholder="请输入用户名-模糊查询"
        />
      </el-form-item>
      <el-form-item label="策略id" prop="strategyId">
        <el-input
          v-model="queryParams.strategyId"
          placeholder="请输入策略id"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px;"
          suffix-icon="Search"
          :suffix-icon-style="{ color: '#909399' }"
        />
      </el-form-item>
      <el-form-item label="会话标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入会话标题"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px;"
          suffix-icon="Search"
          :suffix-icon-style="{ color: '#909399' }"
          :placeholder="请输入会话标题-模糊查询"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['session:session:add']"
        >新增</el-button>
      </el-col>
      <!-- 取消修改按钮 -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['session:session:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['session:session:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sessionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会话id" align="center" prop="sessionId" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="策略id" align="center" prop="strategyId" />
      <el-table-column label="会话标题" align="center" prop="sessionTitle" />
      <el-table-column label="用户姓名" align="center" prop="username" />
      <el-table-column label="策略名称" align="center" prop="strategyName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 此处若有针对单条数据的修改、删除等操作按钮可按需添加，目前仅保留删除示例 -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['session:session:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加session对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="sessionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户Id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户Id" />
        </el-form-item>
        <el-form-item label="策略id" prop="strategyId">
          <el-input v-model="form.strategyId" placeholder="请输入策略id" />
        </el-form-item>
        <el-form-item label="会话标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入会话标题" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Session">
import { selectExistSession, dynamicSelectSession, insertSession, deleteSessionBySessionId } from "@/api/session/session";

const { proxy } = getCurrentInstance();

const sessionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    userId: null,
    strategyId: null,
    title: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    strategyId: null,
    title: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

// 页面刷新时调用此函数加载初始数据
async function initData() {
  loading.value = true;
  const response = await selectExistSession();
  sessionList.value = response.data;
  total.value = sessionList.value.length;
  loading.value = false;
}

// 页面加载完成后执行初始化数据函数
onMounted(() => {
  initData();
});

// 查询session列表（动态查询，将参数封装成sessionDto对象传递，请求方式为POST）
function getList() {
  const sessionDto = {
    username: queryParams.value.username === undefined? null : queryParams.value.username,
    strategyId: queryParams.value.strategyId === undefined? null : queryParams.value.strategyId,
    title: queryParams.value.title === undefined? null : queryParams.value.title
  };
  loading.value = true;
  dynamicSelectSession(sessionDto).then(response => {
    sessionList.value = response.data;
    total.value = sessionList.value.length;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    strategyId: null,
    title: null
  };
  proxy.resetForm("sessionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据，确保正确获取选中行的id，赋值给ids
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sessionId); // 这里使用 sessionId，根据实际情况，如果你的数据结构中表示id的字段不同需要调整
  single.value = selection.length!= 1;
  multiple.value =!selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加session";
}

// 新增功能相关逻辑完善，点击确定按钮后调用insertSession方法提交数据
/** 提交按钮 */
function submitForm() {
  proxy.$refs["sessionRef"].validate(valid => {
    if (valid) {
      insertSession(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        initData(); // 新增成功后刷新页面展示初始数据
      }).catch((error) => {
        proxy.$modal.msgError("新增失败，请检查输入数据或稍后再试");
        console.error("新增操作出错:", error);
      });
    }
  });
}

// 修改此处的删除按钮操作函数，删除成功后调用initData方法刷新页面展示初始数据
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.sessionId || ids.value; // 使用 sessionId 获取当前行的id，如果没有选中行则使用之前获取到的ids数组中的值（这里确保ids已经正确赋值了）
  if (_ids.length === 0) {
    proxy.$modal.msgError("请选择要删除的数据");
    return;
  }
  proxy.$modal.confirm('是否确认删除会话编号为"' + _ids + '"的数据项？').then(() => {
    return deleteSessionBySessionId(_ids).then(() => {
      initData(); // 这里改为调用initData方法，以刷新页面展示初始的所有存在的会话数据
      proxy.$modal.msgSuccess("删除成功");
    }).catch((error) => {
      proxy.$modal.msgError("删除失败，请稍后再试");
      console.error("删除操作出错:", error);
    });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/session/export', {
...queryParams.value
  }, `session_${new Date().getTime()}.xlsx`)
}

</script>